/**
 * 天空盒管理器 - 基于UnlitDynamicSkybox Shader
 * 支持渐变色模式和CubeMap模式，以及旋转贴图效果
 */

import * as THREE from '../../lib/three/build/three.module.js';

class SkyboxManager {
    constructor(scene, renderer) {
        this.scene = scene;
        this.renderer = renderer;
        this.skybox = null;
        this.material = null;
        this.textureLoader = new THREE.TextureLoader();
        this.cubeTextureLoader = new THREE.CubeTextureLoader();
        
        // Shader参数
        this.params = {
            // 模式切换
            useGradient: true,
            
            // 渐变色参数
            topLine: 0.4,
            skyline: 0.0,
            groundLine: -0.05,
            bottomLine: -0.2,
            
            // 渐变色颜色（默认天空 - 蔚蓝色）
            topColor: new THREE.Color('#1e90ff'),      // 道奇蓝
            middleSkyColor: new THREE.Color('#87ceeb'), // 天空蓝
            skylineColor: new THREE.Color('#b0e2ff'),   // 浅天蓝
            groundColor: new THREE.Color('#d4a574'),    // 暖沙色
            bottomColor: new THREE.Color('#8b7355'),    // 棕褐色
            
            // HDR强度
            topColorIntensity: 1.0,
            middleSkyColorIntensity: 1.0,
            skylineColorIntensity: 1.0,
            groundColorIntensity: 0.8,
            bottomColorIntensity: 0.6,
            
            // 旋转贴图参数
            rotateTexHdr: 1.0,
            rotateIntensity: 0.5,
            heightOffset: 0.138,
            heightScale: 1.0,
            rotateSpeed: 5.0,
            maskRotateSpeed: 1.5,
            
            // FlowMap参数
            useFlowMap: false,
            flowSpeed: 0.1,
            flowStrength: 0.25,
            
            // 贴图
            rotateTex: null,
            rotateMaskTex: null,
            maskFlowMap: null,
            cubeMap: null
        };
        
        this.time = 0;
        this.initSkybox();
    }
    
    /**
     * 初始化天空盒
     */
    initSkybox() {
        console.log('🌌 开始初始化天空盒...');
        
        // 清除场景背景，让天空盒可见
        if (this.scene.background) {
            console.log('🔧 清除场景背景颜色，启用天空盒');
            this.scene.background = null;
        }
        
        // 创建天空盒几何体（大球体，从内部观察）
        const geometry = new THREE.SphereGeometry(500, 64, 64);
        
        // 反转几何体使其从内部可见（在创建Mesh之前）
        geometry.scale(-1, 1, 1);
        
        // 创建自定义Shader材质
        this.material = this.createSkyboxMaterial();
        console.log('✅ 天空盒材质已创建');
        
        // 创建天空盒网格
        this.skybox = new THREE.Mesh(geometry, this.material);
        this.skybox.name = 'DynamicSkybox';
        this.skybox.renderOrder = -9999; // 最先渲染（作为背景）
        this.skybox.frustumCulled = false; // 禁用视锥剔除
        
        this.scene.add(this.skybox);
        console.log('✅ 天空盒已添加到场景');
        console.log('✅ 场景中的天空盒:', this.scene.getObjectByName('DynamicSkybox'));
        
        // 启动更新循环
        this.startUpdateLoop();
        console.log('✅ 天空盒初始化完成');
    }
    
    /**
     * 创建天空盒材质
     */
    createSkyboxMaterial() {
        const vertexShader = `
            varying vec3 vWorldPosition;
            varying vec3 vViewDirection;
            
            void main() {
                vec4 worldPosition = modelMatrix * vec4(position, 1.0);
                vWorldPosition = worldPosition.xyz;
                vViewDirection = normalize(worldPosition.xyz - cameraPosition);
                gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
            }
        `;
        
        const fragmentShader = `
            uniform bool useGradient;
            uniform samplerCube cubeMap;
            
            // 渐变色位置
            uniform float topLine;
            uniform float skyline;
            uniform float groundLine;
            uniform float bottomLine;
            
            // 渐变色颜色
            uniform vec3 topColor;
            uniform vec3 middleSkyColor;
            uniform vec3 skylineColor;
            uniform vec3 groundColor;
            uniform vec3 bottomColor;
            
            // HDR强度
            uniform float topColorIntensity;
            uniform float middleSkyColorIntensity;
            uniform float skylineColorIntensity;
            uniform float groundColorIntensity;
            uniform float bottomColorIntensity;
            
            // 旋转贴图
            uniform sampler2D rotateTex;
            uniform sampler2D rotateMaskTex;
            uniform sampler2D maskFlowMap;
            uniform float rotateTexHdr;
            uniform float rotateIntensity;
            uniform float heightOffset;
            uniform float heightScale;
            uniform float rotateSpeed;
            uniform float maskRotateSpeed;
            uniform float time;
            
            // FlowMap
            uniform bool useFlowMap;
            uniform float flowSpeed;
            uniform float flowStrength;
            
            // 贴图启用标志
            uniform bool hasRotateTex;
            uniform bool hasRotateMaskTex;
            uniform bool hasMaskFlowMap;
            uniform bool hasCubeMap;
            
            varying vec3 vWorldPosition;
            varying vec3 vViewDirection;
            
            #define PI 3.14159265359
            
            // 旋转球面采样坐标
            vec2 rotateBallSampling(vec2 normalizedXZ, float speed) {
                float angle = time * (speed / 360.0) * PI;
                float cosA = cos(angle);
                float sinA = sin(angle);
                vec2 rotated = vec2(
                    normalizedXZ.x * cosA - normalizedXZ.y * sinA,
                    normalizedXZ.x * sinA + normalizedXZ.y * cosA
                );
                float ratio = clamp(rotated.y / rotated.x, -100000000.0, 100000000.0);
                float u = (atan(ratio) - (-0.5 * PI)) / (PI);
                return vec2(u, 0.0);
            }
            
            void main() {
                vec3 viewDir = normalize(vViewDirection);
                float y = viewDir.y;
                
                vec3 finalColor = vec3(0.0);
                
                // 渐变色或CubeMap模式
                if (useGradient) {
                    // 计算渐变色
                    vec3 gradientColor;
                    
                    // 底部到地面
                    float t1 = smoothstep(bottomLine, groundLine, y);
                    gradientColor = mix(bottomColor * bottomColorIntensity, groundColor * groundColorIntensity, t1);
                    
                    // 地面到天际线
                    float t2 = smoothstep(groundLine, skyline, y);
                    gradientColor = mix(gradientColor, skylineColor * skylineColorIntensity, t2);
                    
                    // 天际线到中部天空
                    float t3 = smoothstep(skyline, topLine, y);
                    gradientColor = mix(gradientColor, middleSkyColor * middleSkyColorIntensity, t3);
                    
                    // 中部天空到顶部
                    float t4 = smoothstep(topLine, 1.0, y);
                    gradientColor = mix(gradientColor, topColor * topColorIntensity, t4);
                    
                    finalColor = gradientColor;
                } else if (hasCubeMap) {
                    // CubeMap模式
                    finalColor = textureCube(cubeMap, -viewDir).rgb;
                } else {
                    // 默认天空蓝色
                    finalColor = vec3(0.5, 0.7, 1.0);
                }
                
                // 添加旋转贴图效果
                if (hasRotateTex) {
                    vec2 xz = normalize(vec2(viewDir.x, viewDir.z));
                    float height = y * heightScale + heightOffset;
                    
                    // 计算旋转贴图UV
                    vec2 rotateUV = rotateBallSampling(xz, rotateSpeed);
                    rotateUV.y = height;
                    
                    // 采样旋转贴图
                    vec4 rotateColor = texture2D(rotateTex, rotateUV);
                    // 应用HDR强度（直接乘以，不平方）
                    rotateColor *= rotateTexHdr;
                    
                    // 计算遮罩
                    float mask = 1.0;
                    if (hasRotateMaskTex) {
                        vec2 maskUV = rotateUV;
                        
                        // FlowMap处理
                        if (useFlowMap && hasMaskFlowMap) {
                            vec2 flowUV = rotateBallSampling(xz, maskRotateSpeed);
                            flowUV.y = height;
                            vec2 flowVector = texture2D(maskFlowMap, flowUV).rg;
                            maskUV = mix(maskUV, flowVector, sin(time * flowSpeed) * flowStrength);
                        } else {
                            maskUV = rotateBallSampling(xz, maskRotateSpeed);
                            maskUV.y = height;
                        }
                        
                        mask = texture2D(rotateMaskTex, maskUV).r;
                    }
                    
                    // 只在地平线以上显示旋转贴图
                    float horizonMask = clamp(sign(y), 0.0, 1.0);
                    
                    // 混合旋转贴图（使用rotateIntensity作为混合权重）
                    finalColor = mix(finalColor, finalColor + rotateColor.rgb * mask * horizonMask, rotateIntensity);
                }
                
                gl_FragColor = vec4(finalColor, 1.0);
            }
        `;
        
        return new THREE.ShaderMaterial({
            uniforms: {
                useGradient: { value: this.params.useGradient },
                cubeMap: { value: null },
                
                // 渐变色位置
                topLine: { value: this.params.topLine },
                skyline: { value: this.params.skyline },
                groundLine: { value: this.params.groundLine },
                bottomLine: { value: this.params.bottomLine },
                
                // 渐变色颜色
                topColor: { value: this.params.topColor },
                middleSkyColor: { value: this.params.middleSkyColor },
                skylineColor: { value: this.params.skylineColor },
                groundColor: { value: this.params.groundColor },
                bottomColor: { value: this.params.bottomColor },
                
                // HDR强度
                topColorIntensity: { value: this.params.topColorIntensity },
                middleSkyColorIntensity: { value: this.params.middleSkyColorIntensity },
                skylineColorIntensity: { value: this.params.skylineColorIntensity },
                groundColorIntensity: { value: this.params.groundColorIntensity },
                bottomColorIntensity: { value: this.params.bottomColorIntensity },
                
                // 旋转贴图
                rotateTex: { value: null },
                rotateMaskTex: { value: null },
                maskFlowMap: { value: null },
                rotateTexHdr: { value: this.params.rotateTexHdr },
                rotateIntensity: { value: this.params.rotateIntensity },
                heightOffset: { value: this.params.heightOffset },
                heightScale: { value: this.params.heightScale },
                rotateSpeed: { value: this.params.rotateSpeed },
                maskRotateSpeed: { value: this.params.maskRotateSpeed },
                time: { value: 0 },
                
                // FlowMap
                useFlowMap: { value: this.params.useFlowMap },
                flowSpeed: { value: this.params.flowSpeed },
                flowStrength: { value: this.params.flowStrength },
                
                // 贴图标志
                hasRotateTex: { value: false },
                hasRotateMaskTex: { value: false },
                hasMaskFlowMap: { value: false },
                hasCubeMap: { value: false }
            },
            vertexShader: vertexShader,
            fragmentShader: fragmentShader,
            side: THREE.DoubleSide,  // 双面渲染确保可见
            depthWrite: false,
            depthTest: false,  // 天空盒不需要深度测试
            transparent: false
        });
    }
    
    /**
     * 启动更新循环
     */
    startUpdateLoop() {
        const animate = () => {
            requestAnimationFrame(animate);
            this.time += 0.016; // 约60fps
            if (this.material) {
                this.material.uniforms.time.value = this.time;
            }
        };
        animate();
    }
    
    /**
     * 更新参数
     */
    updateParams(params) {
        console.log('🌌 天空盒更新参数:', params);
        
        Object.assign(this.params, params);
        
        if (!this.material) {
            console.warn('⚠️ 天空盒材质未初始化');
            return;
        }
        
        const uniforms = this.material.uniforms;
        
        // 更新基础参数
        if (params.useGradient !== undefined) {
            uniforms.useGradient.value = params.useGradient;
            console.log('✅ 更新 useGradient:', params.useGradient);
        }
        
        // 更新位置
        if (params.topLine !== undefined) uniforms.topLine.value = params.topLine;
        if (params.skyline !== undefined) uniforms.skyline.value = params.skyline;
        if (params.groundLine !== undefined) uniforms.groundLine.value = params.groundLine;
        if (params.bottomLine !== undefined) uniforms.bottomLine.value = params.bottomLine;
        
        // 更新颜色
        if (params.topColor !== undefined) {
            uniforms.topColor.value.copy(params.topColor);
            console.log('✅ 更新 topColor:', params.topColor.getHexString());
        }
        if (params.middleSkyColor !== undefined) uniforms.middleSkyColor.value.copy(params.middleSkyColor);
        if (params.skylineColor !== undefined) uniforms.skylineColor.value.copy(params.skylineColor);
        if (params.groundColor !== undefined) uniforms.groundColor.value.copy(params.groundColor);
        if (params.bottomColor !== undefined) uniforms.bottomColor.value.copy(params.bottomColor);
        
        // 更新HDR强度
        if (params.topColorIntensity !== undefined) uniforms.topColorIntensity.value = params.topColorIntensity;
        if (params.middleSkyColorIntensity !== undefined) uniforms.middleSkyColorIntensity.value = params.middleSkyColorIntensity;
        if (params.skylineColorIntensity !== undefined) uniforms.skylineColorIntensity.value = params.skylineColorIntensity;
        if (params.groundColorIntensity !== undefined) uniforms.groundColorIntensity.value = params.groundColorIntensity;
        if (params.bottomColorIntensity !== undefined) uniforms.bottomColorIntensity.value = params.bottomColorIntensity;
        
        // 更新旋转贴图参数
        if (params.rotateTexHdr !== undefined) uniforms.rotateTexHdr.value = params.rotateTexHdr;
        if (params.rotateIntensity !== undefined) uniforms.rotateIntensity.value = params.rotateIntensity;
        if (params.heightOffset !== undefined) uniforms.heightOffset.value = params.heightOffset;
        if (params.heightScale !== undefined) uniforms.heightScale.value = params.heightScale;
        if (params.rotateSpeed !== undefined) uniforms.rotateSpeed.value = params.rotateSpeed;
        if (params.maskRotateSpeed !== undefined) uniforms.maskRotateSpeed.value = params.maskRotateSpeed;
        
        // 更新FlowMap参数
        if (params.useFlowMap !== undefined) uniforms.useFlowMap.value = params.useFlowMap;
        if (params.flowSpeed !== undefined) uniforms.flowSpeed.value = params.flowSpeed;
        if (params.flowStrength !== undefined) uniforms.flowStrength.value = params.flowStrength;
        
        this.material.needsUpdate = true;
        console.log('✅ 天空盒参数更新完成');
    }
    
    /**
     * 加载旋转贴图
     */
    loadRotateTexture(url) {
        return new Promise((resolve, reject) => {
            this.textureLoader.load(
                url,
                (texture) => {
                    texture.wrapS = THREE.RepeatWrapping;
                    texture.wrapT = THREE.RepeatWrapping;
                    this.params.rotateTex = texture;
                    this.material.uniforms.rotateTex.value = texture;
                    this.material.uniforms.hasRotateTex.value = true;
                    this.material.needsUpdate = true;
                    resolve(texture);
                },
                undefined,
                reject
            );
        });
    }
    
    /**
     * 加载旋转遮罩贴图
     */
    loadRotateMaskTexture(url) {
        return new Promise((resolve, reject) => {
            this.textureLoader.load(
                url,
                (texture) => {
                    texture.wrapS = THREE.RepeatWrapping;
                    texture.wrapT = THREE.RepeatWrapping;
                    this.params.rotateMaskTex = texture;
                    this.material.uniforms.rotateMaskTex.value = texture;
                    this.material.uniforms.hasRotateMaskTex.value = true;
                    this.material.needsUpdate = true;
                    resolve(texture);
                },
                undefined,
                reject
            );
        });
    }
    
    /**
     * 加载FlowMap贴图
     */
    loadFlowMapTexture(url) {
        return new Promise((resolve, reject) => {
            this.textureLoader.load(
                url,
                (texture) => {
                    texture.wrapS = THREE.RepeatWrapping;
                    texture.wrapT = THREE.RepeatWrapping;
                    this.params.maskFlowMap = texture;
                    this.material.uniforms.maskFlowMap.value = texture;
                    this.material.uniforms.hasMaskFlowMap.value = true;
                    this.material.needsUpdate = true;
                    resolve(texture);
                },
                undefined,
                reject
            );
        });
    }
    
    /**
     * 加载CubeMap
     */
    loadCubeMap(urls) {
        return new Promise((resolve, reject) => {
            this.cubeTextureLoader.load(
                urls,
                (texture) => {
                    this.params.cubeMap = texture;
                    this.material.uniforms.cubeMap.value = texture;
                    this.material.uniforms.hasCubeMap.value = true;
                    this.material.needsUpdate = true;
                    resolve(texture);
                },
                undefined,
                reject
            );
        });
    }
    
    /**
     * 获取当前配置
     */
    getConfig() {
        return {
            useGradient: this.params.useGradient,
            topLine: this.params.topLine,
            skyline: this.params.skyline,
            groundLine: this.params.groundLine,
            bottomLine: this.params.bottomLine,
            topColor: '#' + this.params.topColor.getHexString(),
            middleSkyColor: '#' + this.params.middleSkyColor.getHexString(),
            skylineColor: '#' + this.params.skylineColor.getHexString(),
            groundColor: '#' + this.params.groundColor.getHexString(),
            bottomColor: '#' + this.params.bottomColor.getHexString(),
            topColorIntensity: this.params.topColorIntensity,
            middleSkyColorIntensity: this.params.middleSkyColorIntensity,
            skylineColorIntensity: this.params.skylineColorIntensity,
            groundColorIntensity: this.params.groundColorIntensity,
            bottomColorIntensity: this.params.bottomColorIntensity,
            rotateTexHdr: this.params.rotateTexHdr,
            rotateIntensity: this.params.rotateIntensity,
            heightOffset: this.params.heightOffset,
            heightScale: this.params.heightScale,
            rotateSpeed: this.params.rotateSpeed,
            maskRotateSpeed: this.params.maskRotateSpeed,
            useFlowMap: this.params.useFlowMap,
            flowSpeed: this.params.flowSpeed,
            flowStrength: this.params.flowStrength
        };
    }
    
    /**
     * 应用配置
     */
    applyConfig(config) {
        const params = {};
        
        if (config.useGradient !== undefined) params.useGradient = config.useGradient;
        if (config.topLine !== undefined) params.topLine = config.topLine;
        if (config.skyline !== undefined) params.skyline = config.skyline;
        if (config.groundLine !== undefined) params.groundLine = config.groundLine;
        if (config.bottomLine !== undefined) params.bottomLine = config.bottomLine;
        
        if (config.topColor !== undefined) params.topColor = new THREE.Color(config.topColor);
        if (config.middleSkyColor !== undefined) params.middleSkyColor = new THREE.Color(config.middleSkyColor);
        if (config.skylineColor !== undefined) params.skylineColor = new THREE.Color(config.skylineColor);
        if (config.groundColor !== undefined) params.groundColor = new THREE.Color(config.groundColor);
        if (config.bottomColor !== undefined) params.bottomColor = new THREE.Color(config.bottomColor);
        
        if (config.topColorIntensity !== undefined) params.topColorIntensity = config.topColorIntensity;
        if (config.middleSkyColorIntensity !== undefined) params.middleSkyColorIntensity = config.middleSkyColorIntensity;
        if (config.skylineColorIntensity !== undefined) params.skylineColorIntensity = config.skylineColorIntensity;
        if (config.groundColorIntensity !== undefined) params.groundColorIntensity = config.groundColorIntensity;
        if (config.bottomColorIntensity !== undefined) params.bottomColorIntensity = config.bottomColorIntensity;
        
        if (config.rotateTexHdr !== undefined) params.rotateTexHdr = config.rotateTexHdr;
        if (config.rotateIntensity !== undefined) params.rotateIntensity = config.rotateIntensity;
        if (config.heightOffset !== undefined) params.heightOffset = config.heightOffset;
        if (config.heightScale !== undefined) params.heightScale = config.heightScale;
        if (config.rotateSpeed !== undefined) params.rotateSpeed = config.rotateSpeed;
        if (config.maskRotateSpeed !== undefined) params.maskRotateSpeed = config.maskRotateSpeed;
        
        if (config.useFlowMap !== undefined) params.useFlowMap = config.useFlowMap;
        if (config.flowSpeed !== undefined) params.flowSpeed = config.flowSpeed;
        if (config.flowStrength !== undefined) params.flowStrength = config.flowStrength;
        
        this.updateParams(params);
    }
    
    /**
     * 调试：检查天空盒状态
     */
    debugStatus() {
        console.log('=== 🌌 天空盒状态调试 ===');
        console.log('天空盒对象:', this.skybox);
        console.log('天空盒在场景中:', this.scene.getObjectByName('DynamicSkybox'));
        console.log('材质:', this.material);
        console.log('场景背景:', this.scene.background);
        console.log('当前参数:', this.params);
        
        if (this.material && this.material.uniforms) {
            console.log('Uniforms:');
            console.log('- useGradient:', this.material.uniforms.useGradient.value);
            console.log('- topColor:', this.material.uniforms.topColor.value);
            console.log('- middleSkyColor:', this.material.uniforms.middleSkyColor.value);
            console.log('- topLine:', this.material.uniforms.topLine.value);
            console.log('- skyline:', this.material.uniforms.skyline.value);
        }
        console.log('===========================');
    }
    
    /**
     * 强制刷新天空盒渲染
     */
    forceRefresh() {
        console.log('🔄 强制刷新天空盒...');
        
        // 清除场景背景
        this.scene.background = null;
        
        // 强制更新材质
        if (this.material) {
            this.material.needsUpdate = true;
            console.log('✅ 材质已标记为需要更新');
        }
        
        // 强制更新网格
        if (this.skybox) {
            this.skybox.visible = false;
            setTimeout(() => {
                this.skybox.visible = true;
                console.log('✅ 天空盒可见性已切换');
            }, 10);
        }
    }
    
    /**
     * 测试天空盒 - 强制设置为明显的颜色
     */
    testSkybox() {
        console.log('🧪 测试天空盒 - 设置为彩色渐变');
        
        // 清除场景背景
        this.scene.background = null;
        
        // 强制设置为明显的颜色
        this.updateParams({
            useGradient: true,
            topColor: new THREE.Color(1, 0, 0),        // 红色
            middleSkyColor: new THREE.Color(0, 1, 0),  // 绿色
            skylineColor: new THREE.Color(0, 0, 1),    // 蓝色
            groundColor: new THREE.Color(1, 1, 0),     // 黄色
            bottomColor: new THREE.Color(1, 0, 1),     // 紫色
            topColorIntensity: 1.0,
            middleSkyColorIntensity: 1.0,
            skylineColorIntensity: 1.0,
            groundColorIntensity: 1.0,
            bottomColorIntensity: 1.0
        });
        
        // 强制刷新
        this.forceRefresh();
        
        console.log('✅ 如果看到彩色天空，说明天空盒正常工作');
        console.log('✅ 如果没看到，请检查相机位置和场景设置');
    }
    
    /**
     * 销毁天空盒
     */
    dispose() {
        if (this.skybox) {
            this.scene.remove(this.skybox);
            this.skybox.geometry.dispose();
            this.material.dispose();
            
            if (this.params.rotateTex) this.params.rotateTex.dispose();
            if (this.params.rotateMaskTex) this.params.rotateMaskTex.dispose();
            if (this.params.maskFlowMap) this.params.maskFlowMap.dispose();
            if (this.params.cubeMap) this.params.cubeMap.dispose();
        }
    }
}

export default SkyboxManager;
